using System;
using System.IO;
using System.Windows.Forms;
using System.Xml;

namespace FileBrowserApp
{
    public partial class FileBrowserForm : Form
    {
        public FileBrowserForm()
        {
            InitializeComponent();
            InitializeTreeAndList();
        }

        private void InitializeTreeAndList()
        {
            treeView1.Dock = DockStyle.Left;
            listbox1.Dock = DockStyle.Fill;

            treeView1.AfterSelect += TreeView1_AfterSelect;
            treeView1.NodeMouseDoubleClick += TreeView1_NodeMouseDoubleClick;

            PopulateTreeView();
        }

        private void PopulateTreeView()
        {
            treeView1.Nodes.Clear();
            TreeNode rootNode = new TreeNode(Path.GetFileName(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)));
            treeView1.Nodes.Add(rootNode);
            AddFoldersToTree(rootNode, Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
            rootNode.Expand();
        }

        private void AddFoldersToTree(TreeNode parentNode, string path)
        {
            try
            {
                string[] directories = Directory.GetDirectories(path);
                foreach (string directory in directories)
                {
                    TreeNode node = new TreeNode(Path.GetFileName(directory));
                    parentNode.Nodes.Add(node);
                }
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show("无法访问该目录", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void TreeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            listbox1.Items.Clear();
            string selectedPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), GetFullPathFromNode(treeView1.SelectedNode));

            try
            {
                if (Directory.Exists(selectedPath))
                {
                    string[] directories = Directory.GetDirectories(selectedPath);
                    string[] files = Directory.GetFiles(selectedPath);

                    foreach (string directory in directories)
                    {
                        listbox1.Items.Add(Path.GetFileName(directory) + @"\");
                    }

                    foreach (string file in files)
                    {
                        listbox1.Items.Add(Path.GetFileName(file));
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show("无法访问该目录", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private string GetFullPathFromNode(TreeNode node)
        {
            string path = node.Text;
            while (node.Parent != null)
            {
                node = node.Parent;
                path = node.Text + @"\" + path;
            }
            return path;
        }

        private void TreeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Nodes.Count == 0 && e.Node.Text.EndsWith(".xml"))
            {
                string selectedPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), GetFullPathFromNode(e.Node));
                ParseXml(selectedPath);
            }
        }

        private void ParseXml(string filePath)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(filePath);

                listbox1.Items.Clear();
                ExtractElements(xmlDoc.DocumentElement);
            }
            catch (XmlException)
            {
                MessageBox.Show("无法解析XML文件", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ExtractElements(XmlNode node)
        {
            if (node == null) return;

            listbox1.Items.Add($"元素: {node.Name}, 属性: {GetAttributes(node)}, 文本: {node.InnerText}");

            foreach (XmlNode childNode in node.ChildNodes)
            {
                ExtractElements(childNode);
            }
        }

        private string GetAttributes(XmlNode node)
        {
            if (node.Attributes == null) return string.Empty;

            string attributes = string.Empty;
            foreach (XmlAttribute attr in node.Attributes)
            {
                attributes += $"{attr.Name}: {attr.Value}, ";
            }
            return attributes.TrimEnd(',', ' ');
        }
    }

    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FileBrowserForm());
        }
    }
}
